<?php

namespace shenyewangyue\UEditor;

use OSS\OssClient;
use OSS\Core\OssException;


class Oss
{
    public $accessKeyId = "";
    public $accessKeySecret = "";
    public $endpoint = "";
    public $bucket = '';
    public $url = '';
    public $ossClient = '';

//    public $allowFiles = '';
//    public $listSize = '';
//    public $path = '';
//    public $request = '';


    public function __construct()
    {
        $aliyunoss_config       = config('filesystems.disks.aliyunoss');
        $this->accessKeyId      = $aliyunoss_config['accessKeyId'];
        $this->accessKeySecret  = $aliyunoss_config['accessKeySecret'];
        $this->endpoint         = $aliyunoss_config['endpoint'];
        $this->bucket           = $aliyunoss_config['bucket'];
        $this->url              = $aliyunoss_config['url'];

        $this->ossClient = new OssClient($this->accessKeyId, $this->accessKeySecret, $this->endpoint, false);
    }

    /**
     * 把本地变量的内容到文件
     * 简单上传,上传指定变量的内存值作为object的内容
     */
    public function putObject($object, $imgPath)
    {
        $content = file_get_contents($imgPath); // 把当前文件的内容获取到传入文件中
        $options = array();
        try {
            $this->ossClient->putObject($this->bucket, $object, $content, $options);
        } catch (OssException $e) {
            return $e->getMessage();
        }
        return TRUE;
    }

    /**
     * 上传指定的本地文件内容
     */
    public function uploadFile($imgPath, $object) //$_FILES['img']['tmp_name']
    {
        $filePath = $imgPath;
        $options = array();
        try {
            $this->ossClient->uploadFile($this->bucket, $object, $filePath, $options);
        } catch (OssException $e) {
            return $e->getMessage();
        }
        unlink($filePath);
        return TRUE;
    }

    // 删除对象
    public function deleteObject($object)
    {
        try {
            $this->ossClient->deleteObject($this->bucket, $object);
        } catch (OssException $e) {
            return $e->getMessage();
        }
        return TRUE;
    }

    // 判断对象是否存在
    public function doesObjectExist($object)
    {
        try {
            $result = $this->ossClient->doesObjectExist($this->bucket, $object);
        } catch (OssException $e) {
            return $e->getMessage();
        }
        return $result;
    }

    // 批量删除对象
    public function deleteObjects($objects)
    {
        try {
            $this->ossClient->deleteObjects($this->bucket, $objects);
        } catch (OssException $e) {
            return $e->getMessage();
        }
        return TRUE;
    }

    /**
     * 获取object的内容
     *
     * @param OssClient $ossClient OssClient实例
     * @param string $bucket 存储空间名称
     * @return null
     */
    public function getObject($object)
    {
        $options = array();
        try {
            $content = $this->ossClient->getObject($this->bucket, $object, $options);
        } catch (OssException $e) {
            return $e->getMessage();
        }
        // file_get_contents
        return $content;
    }


    public function getList($allowFiles, $listSize, $path, $request){

        $this->allowFiles = substr(str_replace(".", "|", join("", $allowFiles)), 1);
        $this->listSize = $listSize;
        $this->path = trim($path,'/');
        $this->request = $request;

        $size = $this->request->get('size', $this->listSize);
        $start = $this->request->get('start', '');
        if($start == 0){
            $start = '';
        }
        $nextMarker = $start;
//        dd($this->path);
        $lists = [];
        while (true) {
            try {
                $options = array(
                    'prefix' => $this->path,
                    'delimiter' => '',
                    'max-keys' => $size,
                    'marker' => $nextMarker,
                );
                $listObjectInfo = $this->ossClient->listObjects($this->bucket, $options);
            } catch (OssException $e) {
                return [];
            }
            // 得到nextMarker，从上一次listObjects读到的最后一个文件的下一个文件开始继续获取文件列表。
            $nextMarker = $listObjectInfo->getNextMarker();
            $listObject = $listObjectInfo->getObjectList();
            $listPrefix = $listObjectInfo->getPrefixList();
            if (!empty($listObject)) {
//                print("objectList:\n");
                foreach ($listObject as $objectInfo) {
//                    print($objectInfo->getKey() . "\n");
                    $lists[] = [
                        "url"=>$this->url.'/'.$objectInfo->getKey(),
                        "size"=>$objectInfo->getSize(),
                        "mtime"=> strtotime($objectInfo->getLastModified()),
                    ];
                }
            }
            if ($listObjectInfo->getIsTruncated() !== "true") {
                break;
            }
        }
        /* 返回数据 */
        $result = [
            "state" => "SUCCESS",
            "list" => $lists,
            "start" => $nextMarker,
            "total" => count($lists)
        ];
        return $result;
    }
}
